package com.woniu.ucenterservice.web;


import com.github.pagehelper.PageInfo;
import com.woniu.commom.returnvalue.RestResult;
import com.woniu.ucenterservice.pojo.*;
import com.woniu.ucenterservice.service.MessageService;
import com.woniu.ucenterservice.service.MyGoods;
import com.woniu.ucenterservice.service.TsService;
import com.woniu.ucenterservice.service.UserService;
import com.woniu.ucenterservice.vo.MessageVo;
import com.woniu.ucenterservice.vo.TsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author bystander
 * @date 2018/9/29
 */
@Controller

public class UserController {


    @Autowired
    private UserService userService;
    @Autowired
    private MessageService messageService;
    @Autowired
    MyGoods myGoods;
    @Autowired
    TsService tsService;

    /**
     * 校验数据
     *
     * @param data
     * @param type
     * @return
     */
    @GetMapping("/check/{data}/{type}")
    @ResponseBody
    public ResponseEntity<Boolean> checkData(@PathVariable("data") String data, @PathVariable("type") Integer type) {
        return ResponseEntity.ok(userService.checkData(data, type));
    }

    /**
     * 发送验证码
     * @param phone
     * @/user/send
     */
//    @PostMapping("/user/send")
//    public ResponseEntity<Void> sendVerifyCode(@RequestParam("phone")String phone) {
//        userService.sendVerifyCode(phone);
//        return ResponseEntity.noContent().build();
//    }

    /**
     * 用户注册
     *
     * @param user
     * @return
     */
    @PostMapping("/user/register")
    @ResponseBody
    public ResponseEntity<Void> register(@Valid User user, @RequestParam("code") String code) {
        userService.register(user, code);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    /**
     * 根据用户名和密码查询用户
     *
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/user/login")
    @ResponseBody
    public ResponseEntity<User> queryUser(@RequestParam("username") String username, @RequestParam("password") String password, ModelAndView mv,
                                          HttpSession session) {
        User user = userService.queryUser(username, password);
        if (user != null) {
            session.setAttribute("user", user);


        }
        return ResponseEntity.ok(userService.queryUser(username, password));

    }

    @GetMapping("/user/loginOut")

    public ModelAndView loginOut(ModelAndView mv, HttpSession session) {

        session.invalidate();
        mv.setViewName("redirect:/login");
        return mv;

    }

    @RequestMapping("/center/index")
    public ModelAndView ee(HttpSession session) {
        ModelAndView mv = new ModelAndView();
        if (session.getAttribute("user") != null) {
            mv.setViewName("sys/index");
            System.out.println("0000" + session.getAttribute("user"));
        } else {
            mv.setViewName("redirect:/login");
        }
        return mv;

    }

    @GetMapping("/selectMessage")
    @ResponseBody
    public RestResult messages(HttpSession session, @RequestParam(value = "page", defaultValue = "1", required = false) Integer currentPage,
                               @RequestParam(value = "limit", defaultValue = "5", required = false) Integer pageSize
            , MessageVo vo) {
        User user = (User) session.getAttribute("user");
        System.out.println(currentPage);

        System.out.println(pageSize);

        List<Message> messages = messageService.selectAll(user.getUserId(), currentPage, pageSize, vo);
        System.out.println("ooo99" + messages);
        PageInfo pageInfo = new PageInfo(messages);


        return RestResult.success(pageInfo);
    }

    @PostMapping("/fixpwd")
    @ResponseBody
    public RestResult fixpwd(HttpSession session, String oldpassword, String newpassword) {
        User user = (User) session.getAttribute("user");
        String username = user.getUsername();
        userService.fixPassWord(username, oldpassword, newpassword);
        return RestResult.success("修改成功");

    }

    @PostMapping("/findpwd")
    @ResponseBody
    public RestResult findpwd(HttpSession session, String pwd) {

        try {
            User user = (User) session.getAttribute("user");
            String username = user.getUsername();
            userService.findPwd(username, pwd);
            System.out.println(111);
        } catch (Exception e) {
            System.out.println(e);
            return RestResult.failed("密码重置失败");
        }
        return RestResult.success("密码重置成功");
    }

    @PostMapping("/isCode")
    @ResponseBody
    public RestResult isCode(String email, String verCode) {

        try {
            userService.isCode(email, verCode);
            System.out.println(12);
        } catch (Exception e) {
            System.out.println(e);
            return RestResult.failed("验证码错误");
        }
        return RestResult.success("验证码正确");
    }

    @PostMapping("/send")
    public ResponseEntity<Void> sendVerifyCode(@RequestParam("phone") String phone) {
        userService.sendVerifyCode(phone);
        return ResponseEntity.noContent().build();
    }

    @GetMapping("/detailMessage/{typeId}")
    public ModelAndView userEdit(@PathVariable("typeId") Integer typeId, ModelAndView modelAndView) {
        Type type = (Type) messageService.selectMessageContent(typeId);
        modelAndView.addObject("type", type);
        System.out.println(type.toString());
        modelAndView.setViewName("sys/messageDetail");
        return modelAndView;
    }

    @DeleteMapping("/delete/{messageId}")
    @ResponseBody
    public RestResult delete(@PathVariable("messageId") Integer messageId) {

        try { //ctrl +alt + t
            messageService.delectMessage(messageId);
        } catch (Exception e) {
            e.printStackTrace();
            return RestResult.failed("删除失败");
        }
        return RestResult.success("删除成功");
    }

    @DeleteMapping("/deleteAll/{keys}")
    @ResponseBody
    public RestResult deleteUser(@PathVariable("keys") String keys) {
        String[] arr = keys.split(",");
        List<Integer> list = new ArrayList();
        for (String id : arr) {
            list.add(Integer.parseInt(id));
        }
        try { //ctrl +alt + t
            messageService.batchDeleteUser(list);
        } catch (Exception e) {
            e.printStackTrace();
            return RestResult.failed("删除失败");
        }
        return RestResult.success("删除成功");
    }

    @GetMapping("/mygoods")
    @ResponseBody
    public RestResult myGoods(HttpSession session) {
        User user = (User) session.getAttribute("user");


        List<Goods> goods = myGoods.selectMyGoods(user.getUserId());
        PageInfo pageInfo = new PageInfo(goods);
        return RestResult.success(pageInfo);
    }

    @GetMapping("/myfavgoods")
    @ResponseBody
    public RestResult myFavGoods(HttpSession session) {
        User user = (User) session.getAttribute("user");


        List<Goods> goods = myGoods.selectFavGoods(user.getUserId());
        PageInfo pageInfo = new PageInfo(goods);
        return RestResult.success(pageInfo);
    }

    @DeleteMapping("/deleteMyFav/{goodsId}")
    @ResponseBody
    public RestResult deleteMyfav(@PathVariable("goodsId") Integer goodsId) {

        try { //ctrl +alt + t
            myGoods.deleteMyfav(goodsId);
        } catch (Exception e) {
            e.printStackTrace();
            return RestResult.failed("删除失败");
        }
        return RestResult.success("删除成功");
    }

    @DeleteMapping("/deleteAllMyFav/{keys}")
    @ResponseBody
    public RestResult deleteAllMyFav(@PathVariable("keys") String keys) {
        String[] arr = keys.split(",");
        List<Integer> list = new ArrayList();
        for (String id : arr) {
            list.add(Integer.parseInt(id));
        }
        try { //ctrl +alt + t
            myGoods.batchDeleteMyFav(list);
        } catch (Exception e) {
            e.printStackTrace();
            return RestResult.failed("删除失败");
        }
        return RestResult.success("删除成功");
    }

    @DeleteMapping("/deleteMyGoods/{goodsId}")
    @ResponseBody
    public RestResult deleteMyGoods(@PathVariable("goodsId") Integer goodsId) {

        try { //ctrl +alt + t
            myGoods.deleteMyGoods(goodsId);
        } catch (Exception e) {
            e.printStackTrace();
            return RestResult.failed("删除失败");
        }
        return RestResult.success("删除成功");
    }

    @DeleteMapping("/deleteAllMyGoods/{keys}")
    @ResponseBody
    public RestResult deleteAllMyGoods(@PathVariable("keys") String keys) {
        String[] arr = keys.split(",");
        List<Integer> list = new ArrayList();
        for (String id : arr) {
            list.add(Integer.parseInt(id));
        }
        try { //ctrl +alt + t
            myGoods.batchDeleteMyGoods(list);
        } catch (Exception e) {
            e.printStackTrace();
            return RestResult.failed("删除失败");
        }
        return RestResult.success("删除成功");
    }

    @GetMapping("/myhistory")
    @ResponseBody
    public RestResult myHistory(HttpSession session) {
        User user = (User) session.getAttribute("user");


        List<History> histories = myGoods.selectAll(user.getUserId());
        PageInfo pageInfo = new PageInfo(histories);
        return RestResult.success(pageInfo);
    }

    @PostMapping("/addTs")
    @ResponseBody
    public RestResult addTs(HttpSession session, String tContent) {
        User user = (User) session.getAttribute("user");
        Ts ts = new Ts();
        // ts.setTid(1);
        ts.settContent(tContent);
        ts.settStatus("未处理");
        ts.settTime(new Date());
        ts.settUser(user.getUsername());

        try {
            tsService.addTs(ts);
        } catch (Exception e) {
            e.printStackTrace();
            return RestResult.failed("系统出错");
        }

        return RestResult.success("投诉成功");
    }

    @GetMapping("/selectTs")
    @ResponseBody
    public RestResult selectTs(HttpSession session, @RequestParam(value = "page", defaultValue = "1", required = false) Integer currentPage,
                               @RequestParam(value = "limit", defaultValue = "5", required = false) Integer pageSize, TsVo tsVo) {
        User user = (User) session.getAttribute("user");
        try {
            List<Ts> ts = tsService.selectAll(user.getUsername(),currentPage,pageSize,tsVo);
            PageInfo pageInfo = new PageInfo(ts);
            return RestResult.success(pageInfo);

        } catch (Exception e) {
            e.printStackTrace();
            return RestResult.failed("系统出错");
        }

    }

    @GetMapping("/selectCts/{tid}")
    @ResponseBody
    public ModelAndView selectCts(HttpSession session, @PathVariable("tid") Integer tid, ModelAndView mv) {
        User user = (User) session.getAttribute("user");

        Cts cts = tsService.selectCts(tid);
        if (cts != null) {
            mv.addObject("cts", cts);
            mv.setViewName("sys/cts");
            return mv;
        }

        mv.setViewName("sys/ctsnull");
        return mv;


    }
}
